package com.yiwenup.leetcode.hot;

import com.yiwenup.leetcode.TreeNode;

/**
 * 文件描述
 *
 * @Project struct-algorithm
 * @Package com.yiwenup.leetcode.hot
 * @Author yiwenup
 * @Date 2022-04-17 20:03:17
 * @Description https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
 */
public class No0236 {

    /**
     * 执行用时：6 ms, 在所有 Java 提交中击败了100.00%的用户
     * 内存消耗：42.8 MB, 在所有 Java 提交中击败了30.49%的用户
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null) {
            return right;
        }
        if (right == null) {
            return left;
        }
        return root;
    }
}
